package com.data.JVM;

/** 验证finalize方法
 * Created by wangbing on 2018/6/1.
 */
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive(){
        System.out.println("yes,i am still alive!");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize  method executed!");
        // 将自己赋值给某个类的变量或者对象的成员变量
        //
        FinalizeEscapeGC.SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();

        //对象第一次拯救自己
        SAVE_HOOK = null;
        System.gc();

        // 因为finalize方法优先级很低，所以暂停等待

        Thread.sleep(5000);

        if (SAVE_HOOK!=null){
            SAVE_HOOK.isAlive();
        }
        else {
            System.out.println("i am dead!  one****");
        }


        //对象第二次拯救自己
        SAVE_HOOK = null;
        System.gc();

        // 因为finalize方法优先级很低，所以暂停等待

        Thread.sleep(5000);

        if (SAVE_HOOK!=null){
            SAVE_HOOK.isAlive();
        }
        else {
            System.out.println("i am dead! two****");
        }
    }
}
